package com.seabook.calparser.main;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimerTask;

import javax.mail.MessagingException;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.StopWatch;
import org.springframework.util.StopWatch.TaskInfo;

import com.seabook.calparser.pojo.CalParserConfig;

public class CalReportMailTask extends TimerTask implements InitializingBean {
	private CalReportMailer mailer;
	private CalParserConfig config;
	
	private StopWatch sw = new StopWatch();

	@Override
	public void run() {
		try {
			sw.start("MailTask-" + parseDateFormat(new Date()));
			mailer.sendMessage(config);
			sw.stop();
			printMailTaskLogInfo(sw);
		} catch (MessagingException e) {
			e.printStackTrace();
		}
	}
	
	private String parseDateFormat(Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
		return sdf.format(date);
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		// TODO Auto-generated method stub
		
	}
	
	private void  printMailTaskLogInfo(StopWatch sw) {
		int taskCount = sw.getTaskCount();
		TaskInfo taskInfo = sw.getTaskInfo()[taskCount-1];
		String taskName = taskInfo.getTaskName();
		double taskTimeSeconds = taskInfo.getTimeSeconds();
		System.out.println("Taskname:" + taskName + " TaskTimeSeconds:" + taskTimeSeconds + "s TotalTaskNumbers:" + taskCount + " TotalTasksTime:" + sw.getTotalTimeSeconds() + "s");
		
	}

	public CalReportMailer getMailer() {
		return mailer;
	}

	public void setMailer(CalReportMailer mailer) {
		this.mailer = mailer;
	}

	public CalParserConfig getConfig() {
		return config;
	}

	public void setConfig(CalParserConfig config) {
		this.config = config;
	}
	
	

}
